import { ArgumentMetadata, HttpException, HttpStatus, Injectable, PipeTransform, BadRequestException } from '@nestjs/common';
import { plainToInstance } from 'class-transformer';
import { validate, ValidationError } from "class-validator";

@Injectable()

// 传输管道参数校验
export class AuthPipe implements PipeTransform {
  async transform(value: any, metadata: ArgumentMetadata) {
    const dto = plainToInstance(metadata.metatype, value);
    const errInfo: ValidationError[] = await validate(dto)
    if (errInfo.length > 0) {
      throw process.env.NODE_ENV ? new HttpException(errInfo, HttpStatus.BAD_REQUEST)
        : new BadRequestException(JSON.stringify(errInfo.shift().constraints))
    }
    return value;
  }
}
